package carlyang;

import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

class Customer implements Serializable {
	public int id;
	public String name;
	public String address;

	public Customer(int id, String name, String address) {
		this.id = id;
		this.name = name;
		this.address = address;
	}

}

public class ObjectSerializationTest {
	public static Path path = Paths.get("E:/adt_workplace/serial.txt");

	public ObjectSerializationTest() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Customer customer = new Customer(1, "carlyang",
				"china guangdong huizhou");
		// Serialize
		try (OutputStream outputStream = Files.newOutputStream(path,
				StandardOpenOption.CREATE);
				ObjectOutputStream objectOutputStream = new ObjectOutputStream(
						outputStream);) {
			// write first object
			objectOutputStream.writeObject(customer);
			// write second object
			objectOutputStream.writeObject("Custom Info");

		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		// Deserialize   Last In First Out
		try (InputStream inputStream = Files.newInputStream(path,
				StandardOpenOption.READ);
				ObjectInputStream objectOutputStream = new ObjectInputStream(
						inputStream);) {
			// read first object
			Customer customer2 = (Customer) objectOutputStream.readObject();
			System.out.println("First Object:");
			System.out.println("id="+customer2.id);
			System.out.println("name="+customer2.name);
			System.out.println("address="+customer2.address);
			// read second object
			System.out.println("Second Object:");
			String infoString = (String)objectOutputStream.readObject();
			System.out.println("info:"+infoString);

		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}
}
